//
//  ImagePreviewViewController.swift
//  SwiftProject
//
//  Created by qindong on 2021/8/5.
//  Copyright © 2021 qindong. All rights reserved.
//

import UIKit

class ImagePreviewViewController: QMUIImagePreviewViewController, QMUIImagePreviewViewDelegate {
    /// 索引label
    private let indexLb = QMUILabel()
    /// 左滑更多事件
    var scrollToDetail : (()->Void)?
    // 图片数据源
    var dataSource : [Any] = []
    // 缩略图
    var sourceImageViewArray : [UIImageView] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func initSubviews() {
        super.initSubviews()
        
        presentingStyle = .zoom
        imagePreviewView.collectionViewLayout.minimumInteritemSpacing = 0
        imagePreviewView.delegate = self
        
        indexLb.textColor = .white
        indexLb.text = "\(imagePreviewView.currentImageIndex)/\(dataSource.count)"
        view.addSubview(indexLb)

        indexLb.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-20)
            make.centerX.equalToSuperview()
        }

        if scrollToDetail != nil {
            let trailer = MJRefreshNormalTrailer(refreshingBlock: { [unowned self] in
                dismiss(animated: true, completion: nil)
                scrollToDetail!()
                imagePreviewView.collectionView.endRefresh()
            })
            trailer.stateLabel?.textColor = .white
            trailer.arrowView?.tintColor = .white
            imagePreviewView.collectionView.mj_trailer = trailer
        }
    }
    
    func numberOfImages(in imagePreviewView: QMUIImagePreviewView!) -> UInt {
        UInt(dataSource.count)
    }
    
    func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView!, assetTypeAt index: UInt) -> QMUIImagePreviewMediaType {
        .image
    }
    
    func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView!, renderZoomImageView zoomImageView: QMUIZoomImageView!, at index: UInt) {
        zoomImageView.reusedIdentifier = index as NSCopying & NSObjectProtocol
        zoomImageView.contentMode = .scaleAspectFit
        if zoomImageView.image != nil {
            return
        } else {
            zoomImageView.image = nil
            switch dataSource[Int(index)] {
            case is UIImage:
                zoomImageView.image = dataSource[Int(index)] as? UIImage
            case is String:
                zoomImageView.showLoading()
                zoomImageView.imageView.setAFImageWith(dataSource[Int(index)] as! String, .zero, sourceImageViewArray[Int(index)].image) { result in
                    if zoomImageView.reusedIdentifier.isEqual(index) {
                        if let image = try? result.get().image {
                            zoomImageView.image = image
                        }
                        zoomImageView.hideEmpty()
                    }
                }
            default:
                break
            }
        }
    }
    
    func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView!, didScrollTo index: UInt) {
        indexLb.text = "\(index + 1)/\(dataSource.count)"
        sourceImageView = { [unowned self] () -> UIView in
            sourceImageViewArray[Int(index)]
        }
    }
    
    func singleTouch(inZooming zoomImageView: QMUIZoomImageView!, location: CGPoint) {
        dismiss(animated: true, completion: nil)
    }
    
    func longPress(inZooming zoomImageView: QMUIZoomImageView!) {
        let actions: [QMUIAlertController.AlertAction] = [
            .action(title: "取消", style : .cancel),
            .action(title: "保存到相册")
        ]
        QMUIAlertController.present(title: "", message: nil, style: .actionSheet, actions: actions).subscribe (onNext: { index in
            if index == 1 {
                if let image = zoomImageView.image {
                    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                    QMUITips.showSucceed("保存成功")
                }
            }
        }).disposed(by: rx.disposeBag)
    }
}
